<?php

/*
 * Created on May 15, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

if (!defined('BASEPATH'))
exit('No direct script access allowed');

class Slider extends MY_Controller {

	function __construct() {
		parent::__construct();
		//$this->load->model('news_model', 'news', true);
		$this->load->model('slider_model', 'slider', true);
		$this->checkLogin();
		$this->load->helper('form');
		$this->template->set_template('admin');
		$this->buildMenu();

	}

	function index() {
		//echo $this->config->item('language');
		//$this->main = '<div> erer erer er </div>';
		//$this->execute();
		//$this->load->view('main', '');
		$this->view();
	}

	function create() {
		$obj = new stdClass();
		$data['id'] = 0;
		$data['url'] = '';
		$data['vi_title'] = '';
		$data['en_title'] = '';
		$data['vi_summary'] = '';
		$data['en_summary'] = '';
		$data['vi_description'] = '';
		$data['en_description'] = '';
		$data['active'] = 1;
		$data['image'] = '';

		$data['date_add'] = date('Y-m-d H:i:s', time());
		$data['date_upd'] = date('Y-m-d H:i:s', time());

		$data['error_message'] = '';
		$data['legend_text'] = 'Create Slider';lang('create_news');
/*
		$config['toolbar'] = array(
		array( 'Source','-',
          'NewPage','Preview','Templates','-',
          'Cut','Copy','Paste','PasteText','PasteFromWord','-',
          'Undo','Redo','-',
          'Find','Replace','-',
          'SelectAll','RemoveFormat','-',
          'Maximize', 'ShowBlocks'),
    '/',
		array('Bold','Italic','Underline','Strike','-',
          'Subscript','Superscript','-',
          'NumberedList','BulletedList','-',
          'Outdent','Indent','Blockquote','-',
          'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-',
          'Link','Unlink','Anchor','-',
          'Image','Flash','Table','HorizontalRule','SpecialChar'
          ),
    '/',
          array('Format','Font','FontSize','-',
          'TextColor','BGColor', 'MediaEmbed')
          );

          $data['config'] = $config;
          $data['base_url'] = base_url();

          $this->load->library('ckeditor');
          $this->load->library('ckFinder');
          $this->template->add_js('asset/ckeditor/ckeditor.js');
          $this->template->add_js('asset/ckfinder/ckfinder.js');
          //configure base path of ckeditor folder
          $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
          $this->ckeditor->config['toolbar'] = 'Full';
          $this->ckeditor->config['language'] = 'en';
          //configure ckfinder with ckeditor config
          $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
	*/

          //$this->template->parse_view('content', 'admin/product/create_product', $data);

          $this->template->parse_view('content', 'admin/slider/create_slider', $data);
          $this->template->render();
	}

	function edit($id) {
		$news = $this->slider->getById($id);
		$data = array();
		if (!$news) {
			redirect('admin/slider/view');
		}
		
		$data = $news;
		
		$data['error_message'] = '';
		$data['legend_text'] = 'Edit Silder'; //lang('edit_news');

		$this->load->library('ckeditor');
		$this->load->library('ckFinder');
		$this->template->add_js('asset/ckeditor/ckeditor.js');
		$this->template->add_js('asset/ckfinder/ckfinder.js');
		//configure base path of ckeditor folder
		$this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
		$this->ckeditor->config['toolbar'] = 'Full';
		$this->ckeditor->config['language'] = 'en';
		//configure ckfinder with ckeditor config
		$this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');

		$config['toolbar'] = array(
		array( 'Source','-',
          'NewPage','Preview','Templates','-',
          'Cut','Copy','Paste','PasteText','PasteFromWord','-',
          'Undo','Redo','-',
          'Find','Replace','-',
          'SelectAll','RemoveFormat','-',
          'Maximize', 'ShowBlocks'),
    '/',
		array('Bold','Italic','Underline','Strike','-',
          'Subscript','Superscript','-',
          'NumberedList','BulletedList','-',
          'Outdent','Indent','Blockquote','-',
          'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-',
          'Link','Unlink','Anchor','-',
          'Image','Flash','Table','HorizontalRule','SpecialChar'
          ),
    '/',
          array('Format','Font','FontSize','-',
          'TextColor','BGColor', 'MediaEmbed')
          );

          $data['config'] = $config;
          $data['base_url'] = base_url();
          $data['site_url'] = site_url();
         

          $this->template->parse_view('content', 'admin/slider/create_slider', $data);
          $this->template->render();

	}

	function view() {

		$this->load->library('pagination');

		$page = (int) $this->uri->segment(4);
		$config['base_url'] = site_url('admin/slider/view/');

		$config['total_rows'] = $this->slider->countAll(-1);
		$config['per_page'] = NUMBER_RECORD_PER_PAGE;
		$config['uri_segment'] = 4;
		$config['first_link'] = 'First';
		
		$this->pagination->initialize($config);

		$items = '';
		$news = $this->slider->getAll($page, $config['per_page'], -1, 1);
		//print_r($news);
		$data['rows'] = $news;
		$this->template->parse_view('content', 'admin/slider/slider_list', $data);
		$this->template->render();
	}

	function save() {
		 
		$txtID = (int) trim($this->input->post('txtID'));
		$txtFriendlyUrl = trim($this->input->post('txtFriendlyUrl'));

		$data = array();
		if ($txtID > 0){
			$news = $this->slider->getById($txtID);

			if (empty($news)) {
				redirect('admin/slider/view');
				return;
			}
			$data = $news;
		}
		else {
			$data['id'] = 0;
			$data['url'] = '';
			$data['image'] = '';

			$images = $this->session->userdata('images');
			if(empty ($images))
			$images = array();
			$data['images'] = $images;
			$image = $this->session->userdata('image_default');
			if(empty ($image))
			$image = '';
			$data['image'] = $image;

		}

		$this->load->helper(array('form', 'url'));

		$this->load->library('form_validation');

		$this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]');
		//$this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]');
		//$this->form_validation->set_rules('txtViSummary', 'lang:vi_summary', 'required|min_length[2]');
		//$this->form_validation->set_rules('txtEnSummary', 'lang:en_summary', 'required|min_length[2]');
		$this->form_validation->set_rules('txtViDescription', 'lang:vi_description', 'required|min_length[2]');

		$data['url'] = trim($this->input->post('txtFriendlyUrl'));
		$data['vi_title'] = trim($this->input->post('txtViName'));
		$data['en_title'] = trim($this->input->post('txtEnName'));
		$data['vi_description'] = trim($this->input->post('txtViDescription'));
		$data['en_description'] = trim($this->input->post('txtEnDescription'));
		$data['active'] = (int) $this->input->post('active');
		//$product->image = '';
		$data['date_upd'] = date('Y-m-d H:i:s', time());
		$error_message = ''; // $this->loadErrorMessage('Thong diep loi.');
		//print_r($_POST);
		$attach_image = false;
		$image_upload = array('error' => false);
		if (isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0) {
			$attach_image = true;
			$image_upload = $this->upload_image('file', SLIDER_IMAGE_PATH /* './Data/Images/Product/' */);
			//print_r($image_upload);
			if ($image_upload['error'])
			$error_message .= $image_upload['message'];
		}

		/* if($attach_image == true AND $image_upload['error']==true){
		 echo 'Not is image'; return;
		 } */

		if ($this->form_validation->run() == FALSE OR ($attach_image == true AND $image_upload['error'] == true)) {

			$error_message = validation_errors() . '<br>' . $error_message;
			//$code = uniqid();
			//$this->session->set_userdata('code', $code);

			$data['error_message'] = '<div style="color:red">' . $error_message . '</div>';
			//if()
			$data['legend_text'] = $txtID > 0 ? lang('edit_news') : lang('create_news');

			$config['toolbar'] = array(
			array( 'Source','-',
          'NewPage','Preview','Templates','-',
          'Cut','Copy','Paste','PasteText','PasteFromWord','-',
          'Undo','Redo','-',
          'Find','Replace','-',
          'SelectAll','RemoveFormat','-',
          'Maximize', 'ShowBlocks'),
    '/',
			array('Bold','Italic','Underline','Strike','-',
          'Subscript','Superscript','-',
          'NumberedList','BulletedList','-',
          'Outdent','Indent','Blockquote','-',
          'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-',
          'Link','Unlink','Anchor','-',
          'Image','Flash','Table','HorizontalRule','SpecialChar'
          ),
    '/',
          array('Format','Font','FontSize','-',
          'TextColor','BGColor')
          );

          $data['config'] = $config;
          $data['base_url'] = base_url();

          $this->load->library('ckeditor');
          $this->load->library('ckFinder');
          $this->template->add_js('asset/ckeditor/ckeditor.js');
          $this->template->add_js('asset/ckfinder/ckfinder.js');
          //configure base path of ckeditor folder
          $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
          $this->ckeditor->config['toolbar'] = 'Full';
          $this->ckeditor->config['language'] = 'en';
          //configure ckfinder with ckeditor config
          $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
          $this->template->parse_view('content', 'admin/slider/create_slider', $data);
          $this->template->render();

          return;
		}
		else {
			 
			$result = 0;
			$insert_id = 0;
			if ($attach_image && !$image_upload['error']){
				if ($txtID > 0 && !empty($data['image'])){
					@unlink(SLIDER_IMAGE_PATH.$data['image']);
				}
				
				$data['image'] = $image_upload['upload_data']['file_name'];
			}
			if ($txtID > 0) {
				$result = $this->slider->update($data);
			} else {

				$data['date_add'] = date('Y-m-d H:i:s', time());
				$txtID = $insert_id = $result = $this->slider->create($data);

			}

			if ($insert_id > 0) {
				 
			}

			redirect('admin/slider/view');
		}
	}


	function uploadFile($config) {

		$this->load->library('upload', $config);
		$result = array('error' => false);

		if (!$this->upload->do_upload('uploadfile')) {
			$result['message'] = $this->upload->display_errors();
			$result['error'] = true;
		} else {
			$result['upload_data'] = $this->upload->data();
		}

		return $result;
	}
	

	function upload_image($field_name, $path) {
		$result = array();
		
		if (!file_exists($path)){
			mkdir($path, "777") ;
		}
		
		
		$config['upload_path'] = $path; //'./Data/Images/';
		$config['allowed_types'] = '*' ; //gif|jpg|png|jpeg';
		//$config['max_size']	= '1000';
		//$config['max_width']  = '1024';
		//$config['max_height']  = '768';
		$config['overwrite'] = true;

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload($field_name)) {
			//$error = array('error' => $this->upload->display_errors());
			$result['error'] = true;
			$result['message'] = $this->upload->display_errors();
			//$this->load->view('upload_form', $error);
		} else {
			//$data = array('upload_data' => $this->upload->data());
			$result['error'] = false;
			$result['upload_data'] = $this->upload->data();
		}

		return $result;
	}

	
	
	function testGetFile() {
		$config = array(
            'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
            'max_size' => 1024000000 /* 1Mb */
		);

		$result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');

		if (!$result['error'])
		echo 'Get file success.';
		else
		echo $result['message'];
	}

	function delete() {
		$id = intval($this->uri->segment(4));
		$ids = array();
		if ($id > 0) {
			$ids[] = $id;
			//$this->product->delete($id);
		} else {
			if (($this->input->post('submitDelcategory'))) {
				$ids = $this->input->post('categoryBox');
			}
		}

		if (count($ids)) {
			// Xoa file anh chinh:
			
			$newses = $this->slider->getAllByIds($ids);
			$main_images = array();
			
			if (count($newses) > 0) {
				for ($i = 0; $i < count($newses); $i++) {
					$main_images[] = $newses[$i]['image'];
				}
			}


			//Xoa san pham
			$result = $this->slider->delete($ids);
			if ($result) {
				if (count($main_images) > 0) {
					for ($i = 0; $i < count($main_images); $i++) {
						@unlink(SLIDER_IMAGE_PATH.$main_images[$i]);
					}
				}				
			}
		}

		redirect('admin/slider');
	}
	
	
function change_order(){
        $id1 = (int)$this->uri->segment(4);
        $id2 = (int)$this->uri->segment(5);

        $cat1 = $this->slider->getById($id1);
        
        $cat2 = $this->slider->getById($id2);

        if($cat1 && $cat2){
            $position1 = $cat1['position'];
            $cat1['position'] = $cat2['position'];
            $cat2['position'] = $position1;
			
            $cat1['date_add'] = date('Y-m-d H:i:s', time());
            $cat2['date_add'] = date('Y-m-d H:i:s', time());
            
            $this->slider->update($cat1);
            $this->slider->update($cat2);

        }

        redirect('admin/slider/view');
    }

}


?>
